<?php

namespace app\api\controller\user;

use app\api\controller\plus\points\Product;
use app\api\model\order\OrderProduct;
use app\api\model\user\User as UserModel;
use app\api\controller\Controller;
use app\api\model\settings\Setting as SettingModel;
use app\common\library\easywechat\AppWx;
use app\common\model\supplier\SupplierCommission;
use app\common\model\user\OwnerEntry;
use app\common\model\product\Product as ProductModel;
use app\common\model\product\Category;
use app\common\model\supplier\CommissionConfig;
use app\Request;
use app\api\model\order\Order as OrderModel;
use app\shop\model\supplier\Supplier as SupplierModel;


use app\api\model\plus\bargain\TaskHelp;

/**
 * 用户管理模型
 */
class User extends Controller
{
    /**
     * 用户自动登录,默认微信小程序
     */
    public function login()
    {
        $model = new UserModel;
        $user_id = $model->login($this->request->post());
        return $this->renderSuccess('', [
            'user_id' => $user_id,
            'token' => $model->getToken()
        ]);
    }

    /**
     *H5登录
     * mobileLogin
     * \think\response\Json
     * @return \think\response\Json
     * @Author kevin
     * @date 2024/6/17 11:30
     */
    public function mobileLogin()
    {
        $model = new UserModel;
        $user_id = $model->mobileLogin($this->request->post());
        return $this->renderSuccess('', [
            'user_id' => $user_id,
            'token' => $model->getToken()
        ]);
    }

    public function appLogin()
    {
        $model = new UserModel;
        $type = $this->request->post('type',1); //1=配送员登录，2=店员登录
        if($type==1){
            $user_id = $model->appLogin($this->request->post());
        }else{
            $user_id = $model->appClerkLogin($this->request->post());
        }

        return $this->renderSuccess('', [
            'user_id' => $user_id,
            'token' => $model->getToken()
        ]);
    }


    /**
     * 当前用户详情
     */
    public function detail()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        $gift_name = SettingModel::getItem('live')['gift_name'];
        return $this->renderSuccess('', compact('userInfo', 'gift_name'));
    }

    public function getSession($code)
    {
        // 微信登录 获取session_key
        $app = AppWx::getApp();
        $session_key = null;
        $session = AppWx::sessionKey($app, $code);
        if ($session != null) {
            $session_key = $session['session_key'];
        }
        return $this->renderSuccess('', compact('session_key'));
    }

    /**
     *业主登记
     * ownerApply
     * @param Request $request
     * \think\response\Json
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @throws \app\common\exception\BaseException
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DbException
     * @Author kevin
     * @date 2024/4/2 17:41
     */
    public function ownerApply(Request $request)
    {
        $param = $request->param();
        $user = $this->getUser();

        $data['user_id'] = $user['user_id'];
        if((new OwnerEntry()) -> where('user_id',$user['user_id']) -> count()){
            return $this->renderError('请勿重复提交');
        }
        $data['mobile'] = $param['mobile'];
        $data['house_number'] = $param['house_number'];
        $data['nickName'] = $param['nickName'];
        if(OwnerEntry::createData($data)){
            return $this->renderSuccess('提交成功');
        }else{
            return $this->renderError('提交失败');
        }
    }

    /**
     *申请状态
     * getOwnerApplyStatus
     * \think\response\Json
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @throws \app\common\exception\BaseException
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DbException
     * @Author kevin
     * @date 2024/4/2 18:02
     */
    public function getOwnerApplyStatus()
    {
        $user = $this->getUser();
        $count = (new OwnerEntry()) -> where('user_id',$user['user_id']) -> count();
        $data['status'] = $count;
        return $this->renderSuccess('', compact('data'));
    }

    /**
     * 绑定手机号
     */
    public function bindMobile()
    {
        $model = $this->getUser();
        if ($model->bindMobile($this->request->post())) {
            return $this->renderSuccess('');
        }
        return $this->renderError('绑定失败');
    }

    /**
     * 修改用户信息
     */
    public function updateInfo()
    {
        // 当前用户信息
        $model = $this->getUser();
        if ($model->edit($this->request->post())) {
            return $this->renderSuccess('修改成功');
        }
        return $this->renderError($model->getError() ?: '修改失败');
    }

    /**
     * 积分转换余额
     */
    public function transPoints($points = 0)
    {
        // 当前用户信息
        $model = $this->getUser();
        if ($model->transPoints($points)) {
            return $this->renderSuccess('转换成功');
        }
        return $this->renderError($model->getError() ?: '转换失败');
    }

    /**
     * 删除账号
     */
    public function deleteAccount()
    {
        $model = new UserModel();
        if ($model->setDelete($this->getUser())) {
            return $this->renderSuccess('删除成功');
        }
        return $this->renderError($model->getError() ?: '删除失败');
    }

    /**
     * @Exp    获取邀请列表数据
     * @Author Mr.Z
     * @Date   2024-02-21
     * @return [type]     [description]
     */
    public function getuserinvitelist(Request $request)
    {
        // 当前用户信息
        $user = $this->getUser();
        $param = $request->param();
        $UserModel = new UserModel();
        $params = [];
        if($param['type']==1){//月
            $params['start_time'] = strtotime(date("Y-m-1",time()));
            $params['end_time'] = time();
        }elseif($param['type']==2){//日
            $params['start_time'] = time();
        }
        $list = $UserModel->getRefereeList($user['user_id'],$params);
        return $this->renderSuccess('', $list);
    }

    /**
     * 推送测试
     * @return void
     */
    public function pushTest(){
        send_unipush_message();
//        (new OrderModel()) -> insertRedisOrder([222]);
//        (new OrderModel()) -> getRedisOrder();
    }

    /**
     * 测试
     * updateProductName
     * void
     * @return void
     * @Author kevin
     * @date 2024/4/22 17:22
     */
    public function updateProductName(){
        $map[] = ['search','=',null];
        $map[] = ['is_delete','=',0];
        ProductModel::where($map) -> chunk(100, function ($products) {
            foreach($products as $product){
                $product_name = preg_replace('/\s/', '',$product['product_name']);
                $product_id = $product['product_id'];
                (new ProductModel()) -> where('product_id',$product_id) -> update(['search' => $product_name]);
            }
        });
    }

    /**
     *更新商品佣金比例
     * updateCommissionRate
     * void
     * @return void
     * @Author kevin
     * @date 2024/4/25 16:46
     */
    public function updateCommissionRate()
    {
        $where[]= ['title','in',['啤酒','饮料','零食']];
        $commission_config = (new CommissionConfig()) -> where($where) -> select()-> toArray();
        foreach ($commission_config as $k => $v){
            $array = [];
            $category_id = (new Category()) -> where('name',$v['title'])  -> where('parent_id',0) -> value('category_id');
            $array = $this -> getCateChild($category_id);
            $array[] = $category_id;

            $commission_config_id = $v['commission_config_id'];
            $map= [];
            $map[] = ['category_id','in',$array];

            (new ProductModel()) -> where( $map) -> update(['commission_config_id' => $commission_config_id]);
            $this -> updateCommissionRate1();
        }

    }

    public function updateCommissionRate1()
    {
        $where[]= ['title','in',['零食']];
        $commission_config = (new CommissionConfig()) -> where($where) -> select()-> toArray();
        foreach ($commission_config as $k => $v){
            $array = [];
            $category = (new Category()) -> where('name','休闲零食')  -> find();
            $array = $this -> getCateChild($category['parent_id']);
            $array[] = $category['parent_id'];

            $commission_config_id = $v['commission_config_id'];
            $map= [];
            $map[] = ['category_id','in',$array];

            (new ProductModel()) -> where( $map) -> update(['commission_config_id' => $commission_config_id]);
        }


    }

    public function getCateChild($category_id)
    {
        return (new Category()) -> where('parent_id',$category_id)  -> column('category_id');
    }

    /**
     *更新佣金
     * updateCommission
     * void
     * @return void
     * @Author kevin
     * @date 2024/4/30 14:09
     */
    public function updateCommission(){
        $model = new SupplierModel;
        $list = $model->getListData([],2);
        foreach ($list as $value){
            $map = [];
            $map[] = ['pay_status','=',20];
            $map[] = ['order_status','=',30];
            $map[] = ['shop_supplier_id','=',$value['shop_supplier_id']];
            $order_list = (new OrderModel()) -> where($map) -> select() -> toArray();
            foreach ($order_list as $v){
                $supplier_commission = [];
                $supplier_commission['shop_supplier_id'] = $v['shop_supplier_id'];
                $supplier_commission['order_id'] = $v['order_id'];
                $supplier_commission['order_no'] = $v['order_no'];
                $supplier_commission['pay_time'] = $v['pay_time'];
                $supplier_commission['pay_price'] = $v['pay_price'];
                $supplier_commission['user_id'] = $v['user_id'];
                $supplier_commission['order_source'] = $v['order_source'];
                $supplier_commission['order_create_time'] = strtotime($v['create_time']);
                $supplier_commission['coupon_id_sys'] = $v['coupon_id_sys'];
                $supplier_commission['total_price'] = $v['total_price'];
                $product_list = (new OrderProduct()) -> where('order_id',$v['order_id']) -> select() -> toArray();
                if($v['refund_money'] > 0 && $v['is_order_refund'] == 2){
                    SupplierCommission::refund($v['order_id'],$v['refund_money']);
                }

                SupplierCommission::createProductData($product_list,$supplier_commission);
            }

        }
    }

    public function updateOrderData(){
        $list = (new OrderModel()) -> where('pay_status',20) -> where('is_order_refund',2) -> select() -> toArray();
        foreach ($list as $value){
//                $supplier_commission['coupon_id_sys'] = $value['coupon_id_sys'];
//                $supplier_commission['total_price'] = $value['online_money'];
                SupplierCommission::refund($value['order_id'],$value['online_money']);
        }
        echo 222;exit;

    }


    public function getTaskHelpList(){

        $list = (new TaskHelp) -> with(['user','activity']) -> select() -> toArray();
        foreach ($list as $key => $value){
            $list[$key]['is_creater_text'] = $value['is_creater']?'是':'否';
            $list[$key]['nickName'] = $value['user']['nickName']??'';
            $list[$key]['mobile'] = $value['user']['mobile']??'';
            $list[$key]['reg_ip'] = $value['user']['reg_ip']??'';
        }
        $xls_cell = [
            ['title' , '活动标题'],
            ['user_id' , '用户ID'],
            ['nickName' , '昵称'],
            ['mobile' , '手机号码'],
            ['reg_ip' , '注册IP'],
            ['is_creater_text' , '受否发起人'],
            ['cut_money' , '砍价金额'],
            ['create_time' , '时间'],
        ];
        $exp_title = '助力记录' . date('Y-m-d H:i:s');
        exportExcel($exp_title, $xls_cell, $list);
    }


}